#coding=utf-8

from common import get_con
from stutils import set_django_environ
set_django_environ()

from stdj.stock.models import *
import datetime
td = datetime.date.today().isoformat()

tb_price = '''
create table if not exists price
(id integer primary key,
 code text not null,
 name text not null,
 
 date text not null,
 
 start real not null,
 end real not null,
 high real not null,
 low real not null,
 
 volume integer not null,
 change real,
 hsl real,
 unique (code, date)
);'''

def adayprice2db(cusor, e):
    
    
def initdb():
    con = get_con()
    cursor = con.cursor()
    cursor.execute(tb_topten)
    
    for s in Share.objects.order_by('code'):
        eds = s.exday_set.filter(date__gte='2004-01-01').filter(date__lte='2007-12-25').order_by('date')
        print s,len(eds)
        
        for e in eds:
            p = e.price
            cursor.execute('insert into price (code, name, date, start, end, high, low, volume)\
                            values(?,?,?,?,?,?,?,?)', 
                            (s.code, s.name, e.date, 
                             float(p.start), float(p.end), float(p.high), float(p.low), 
                             p.volume)
                          )
            if p.change:
                cursor.execute('update price set change=? where code=? and date=?',
                               (float(p.change), s.code, e.date),
                              )
            if p.hsl:
                cursor.execute('update price set hsl=? where code=? and date=?',
                               (float(p.hsl), s.code, e.date),
                              )
        con.commit()
        
def update(exdate=td):
    con = get_con()
    cursor = con.cursor()
    
    for s in Share.objects.order_by('code'):
        try:
            e = s.exday_set.get(date=exdate)
        except Exday.DoesNotExist,e:
            pass
        else:
            p = e.price
            cursor.execute('insert into price (code, name, date, start, end, high, low, volume)\
                            values(?,?,?,?,?,?,?,?)', 
                            (s.code, s.name, e.date, 
                             float(p.start), float(p.end), float(p.high), float(p.low), 
                             p.volume)
                          )
            if p.change:
                cursor.execute('update price set change=? where code=? and date=?',
                               (float(p.change), s.code, e.date),
                              )
            if p.hsl:
                cursor.execute('update price set hsl=? where code=? and date=?',
                               (float(p.hsl), s.code, e.date),
                              )
    con.commit()
    
if __name__ == "__main__":
    initdb()